//
//  SSWebViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/8/21.
//

import UIKit

import WebKit


class SSWebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate {
    var webUrl = ""

    // wkWebView

    lazy var webView: WKWebView = {

            // 创建WKPreferences
        

            let preferences = WKPreferences()

            // 开启js

            preferences.javaScriptEnabled = true

            // 创建WKWebViewConfiguration

            let configuration = WKWebViewConfiguration()

            // 设置WKWebViewConfiguration的WKPreferences

            configuration.preferences = preferences

            // 创建WKUserContentController

            let userContentController = WKUserContentController()

            // 配置WKWebViewConfiguration的WKUserContentController

            configuration.userContentController = userContentController

            // 给WKWebView与Swift交互起一个名字：callbackHandler，WKWebView给Swift发消息的时候会用到

            // 此句要求实现WKScriptMessageHandler协议

            configuration.userContentController.add(self, name: "callbackHandler")

            // 创建WKWebView

            var webView = WKWebView(frame:CGRect.zero, configuration: configuration)

            // 让webview翻动有回弹效果

            webView.scrollView.bounces = true

            // 只允许webview上下滚动

            webView.scrollView.alwaysBounceVertical = true

            // 此句要求实现WKNavigationDelegate协议

            webView.navigationDelegate = self
            webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)

            return webView

        }()

    // 进度条

    lazy var progressView: UIProgressView = {

        var progressView = UIProgressView()

        progressView.progressTintColor = UIColor.clear
//        progressView.progressTintColor = UIColor.red

        progressView.trackTintColor = UIColor.clear

        return progressView

    }()

    override func viewWillDisappear(_ animated: Bool) {

        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")

    }

    override func viewDidLoad() {

        super.viewDidLoad()

        title = "详情"

        self.view.backgroundColor = UIColor.white

        initInterface()

    }

    func initInterface() -> () {

        self.view.addSubview(self.webView);

        self.webView.snp.makeConstraints { (make) in

            make.edges.equalTo(self.view).inset(UIEdgeInsets.init(top: NavAndStatusHeight, left: 0, bottom: 0, right: 0));

        }

        self.webView.sizeToFit();

        //创建网址

//        let url = NSURL(string: "http://www.baidu.com")
        let url = NSURL(string: self.webUrl)

        //创建请求

        let request = NSURLRequest(url: url! as URL)

        //加载请求

        self.webView.load(request as URLRequest)

        self.view .addSubview(progressView);

        self.progressView.snp.makeConstraints { (make) in

            make.top.equalTo(self.view).offset(0)

            make.left.equalTo(self.view).offset(0)

            make.right.equalTo(self.view).offset(0)

            make.height.equalTo(5.0);

        }
        //进度条的进度监听
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)

    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if keyPath == "estimatedProgress" {

            self.progressView.alpha = 1.0

            self.progressView.setProgress(Float(webView.estimatedProgress), animated: true)

            //进度条的值最大为1.0

            if(self.webView.estimatedProgress >= 1.0) {

                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () -> Void in

                    self.progressView.alpha = 0.0

                }, completion: { (finished:Bool) -> Void in

                    self.progressView.progress = 0

                })

            }

        }

    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {    }

    // 加载完毕以后执行，自适应屏幕宽度，有的屏幕不自适应，需要自适应屏幕宽度

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        webView.evaluateJavaScript("""

        var oMeta = document.createElement('meta');

        oMeta.content = 'width=device-width, initial-scale=1, user-scalable=0';

        oMeta.name = 'viewport';

        document.getElementsByTagName('head')[0].appendChild(oMeta);

        """,completionHandler: nil)

    }

    // 处理网页加载失败

    private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError){

        self.progressView.progress = 0

    }

    //处理网页加载完成

    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!){   }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){

        self.progressView.progress = 0

  }

}
